package co.sanduche.teach.old;

import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import co.sanduche.models.Enums.RecipientType;
import co.sanduche.models.Models.Curso;
import co.sanduche.models.Models.Mensaje;
import co.sanduche.models.Models.Recipient;
import co.sanduche.services.EndPoints;
import co.sanduche.teach.LoginActivity;
import co.sanduche.teach.R;
import co.sanduche.teach.R.id;
import co.sanduche.teach.R.layout;
import co.sanduche.teach.R.menu;
import co.sanduche.util.DialogUtil;
import co.sanduche.util.EPCallback;

public class StudentListActivity extends Activity {

	private List<Curso> cursos;
	boolean colegio = true;
	private int curso;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ActionBar actionbar = getActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		setContentView(R.layout.activity_student_list);
		setCurrent("Colegio Crecer");
		FragmentTransaction transaction = getFragmentManager()
				.beginTransaction();
		transaction.add(R.id.mainListContainer, new ClassListFragment())
				.commit();

	}

	protected void setCurrent(String current) {
		TextView lblCurso = (TextView) findViewById(R.id.mainLblCurrent);
		lblCurso.setText(current);
	}

	public class ClassListFragment extends Fragment {

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			ListView listView = new ListView(getActivity());
			final StudentsAdapter<Curso> adapter = new StudentsAdapter<Curso>(
					this, "Curso  ") {
				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) {
					View root;
					if (convertView != null)
						root = convertView;
					else
						root = fragment
								.getActivity()
								.getLayoutInflater()
								.inflate(R.layout.class_list_item_view, parent,
										false);
					TextView lblClass = (TextView) root
							.findViewById(R.id.classLblClass);
					String text = cursos == null ? type + position : cursos
							.get(position).getNombre();
					lblClass.setText(text);

					return root;
				}

			};
			EndPoints.ProfesorEP.getCursos(new EPCallback<List<Curso>>() {

				@Override
				public void onSuccess(List<Curso> arg0) {
					adapter.setDatasource(arg0);
					StudentListActivity.this.cursos = arg0;
				}
			});

			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					StudentListActivity.this.showCurso(position);
				}
			});

			return listView;
		}
	}

	public class StudentListFragment extends Fragment {
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			View root = inflater.inflate(R.layout.fragment_student_list,
					container, false);

			ListView listStudents = (ListView) root
					.findViewById(R.id.studentsListStudents);
			listStudents.setAdapter(new StudentsAdapter(this, "Estudiante ") {
				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) {
					View root;
					if (convertView != null)
						root = convertView;
					else
						root = fragment
								.getActivity()
								.getLayoutInflater()
								.inflate(R.layout.student_list_item_view,
										parent, false);
					TextView lblStudent = (TextView) root
							.findViewById(R.id.studentItemStudentName);
					lblStudent.setText(type + position);
					return root;
				}
			});

			return root;
		}
	}

	public static abstract class StudentsAdapter<T> extends BaseAdapter {

		protected Fragment fragment;
		protected String type;
		private List<T> datasource;

		public StudentsAdapter(Fragment fragment, String type) {
			this.fragment = fragment;
			this.type = type;
		}

		public void setDatasource(List<T> arg0) {
			datasource = arg0;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			if (datasource != null)
				return datasource.size();
			return 10;
		}

		@Override
		public Object getItem(int position) {
			if (datasource != null)
				return datasource.get(position);
			return type + position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// Respond to the action bar's Up/Home button
		case android.R.id.home:
			if (colegio) {
				Intent upIntent = NavUtils.getParentActivityIntent(this);
				if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
					// This activity is NOT part of this app's task, so create a
					// new
					// task
					// when navigating up, with a synthesized back stack.
					TaskStackBuilder.create(this)
					// Add all of this activity's parents to the back stack
							.addNextIntentWithParentStack(upIntent)
							// Navigate up to the closest parent
							.startActivities();
				} else {
					// This activity is part of this app's task, so simply
					// navigate up to the logical parent activity.
					NavUtils.navigateUpTo(this, upIntent);
				}
			} else {
				getFragmentManager()
						.beginTransaction()
						.replace(R.id.mainListContainer,
								new ClassListFragment()).commit();
			}

			return true;
		case R.id.action_send_message:
			Log.i("asdasdsa", "enviando mensaje");
			if (colegio) {
				Mensaje m = new Mensaje();
				final String message = "Suck it school!!! " + new Date();
				m.setMensaje(message);
				Recipient r = new Recipient();
				r.setTipo(RecipientType.COLEGIO);
				r.setIdRecipient(1l);
				m.setRecipients(new HashSet<Recipient>(Arrays.asList(r)));
				EndPoints.MensajeriaEP.sendMessage(m,
						new EPCallback<Mensaje>() {

							@Override
							public void onSuccess(Mensaje arg0) {

								DialogUtil.alert(StudentListActivity.this,
										message);

							}

							@Override
							public void onFailure(Throwable e) {
								super.onFailure(e);
								DialogUtil.alert(StudentListActivity.this,
										"ouch school");
							}
						});
			} else {
				Mensaje m = new Mensaje();
				final String message = "Suck it class!!! " + new Date();
				m.setMensaje(message);
				Recipient r = new Recipient();
				r.setTipo(RecipientType.CURSO);
				r.setIdRecipient(cursos.get(curso).getId());
				m.setRecipients(new HashSet<Recipient>(Arrays.asList(r)));
				EndPoints.MensajeriaEP.sendMessage(m,
						new EPCallback<Mensaje>() {

							@Override
							public void onSuccess(Mensaje arg0) {

								DialogUtil.alert(StudentListActivity.this,
										message);

							}

							@Override
							public void onFailure(Throwable e) {
								super.onFailure(e);
								DialogUtil.alert(StudentListActivity.this,
										"ouch class");
							}
						});

			}
			break;
		case R.id.action_send_photo:
			Log.i("asdasdsa", "enviando foto");
			break;
		case R.id.menu_logout:
			EndPoints.UserEP.logout(new EPCallback<Void>() {

				@Override
				public void onSuccess(Void arg0) {
					EndPoints.UserEP.logout(new EPCallback<Void>() {

						@Override
						public void onSuccess(Void arg0) {

						}
					});
					Intent intent = new Intent(StudentListActivity.this,
							LoginActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
					finish();
				}
			});
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void showCurso(int position) {
		setCurrent("Curso " + position);
		getFragmentManager().beginTransaction()
				.replace(R.id.mainListContainer, new StudentListFragment())
				.addToBackStack(null).commit();
		colegio = false;
		curso = position;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

}
